package com.mijie.homi.service.user;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mijie.homi.common.constant.MCKey;
import com.mijie.homi.common.domain.user.Setting;
import com.mijie.homi.dao.user.SettingDao;
import com.mijie.homi.service.cache.MemcacheService;

@Service
public class SettingService {

	@Autowired
	private SettingDao dao;
	@Autowired
	private MemcacheService mcs;
	private Logger logger = Logger.getLogger(SettingService.class);
	
	public Setting getSettingByUserId(int userId){
		Setting setting = (Setting) mcs.get(MCKey.USER_SETTING, String.valueOf(userId));
		if(setting==null){
			setting = dao.getSettingByUserId(userId);
			if(setting!=null) mcs.set(MCKey.USER_SETTING, String.valueOf(userId), MCKey.USER_CACHE_TIMEOUT, setting);
		}
		return setting;
	}
	
	public int updateSetting(Setting setting){
		int rows =  dao.updateSetting(setting);
		if(rows>0) mcs.delete(MCKey.USER_SETTING, String.valueOf(setting.getUserId()));
		return rows;
	}
	
	
	//用于注册用户时内部Service调用
	@Transactional(rollbackFor={Exception.class})
	public int addSetting(int userId){
		return dao.addSetting(userId);
	}
	
	private int listReceiveNearbyMoodUserIdOffset = 0;
	private int listReceiveNearbyMoodUserIdLimit = 100;
	public List<Setting> listReceiveNearbyMoodUserId(){
		List<Setting> list = null;
		list = dao.listReceiveNearbyMoodUserId(listReceiveNearbyMoodUserIdOffset, listReceiveNearbyMoodUserIdLimit);
		if(list.isEmpty()){
			listReceiveNearbyMoodUserIdOffset = 0;
			list =  dao.listReceiveNearbyMoodUserId(listReceiveNearbyMoodUserIdOffset, listReceiveNearbyMoodUserIdLimit);
			if(list.isEmpty()) list = null;
		}
		listReceiveNearbyMoodUserIdOffset+=listReceiveNearbyMoodUserIdLimit;
		return list;
	}
	
}
